# encoding: UTF-8
'''
预估保证金明细
last update: 2023年5月17日 11:05:57
'''
import tushare as ts
import pandas as pd 
from datetime import date
from datetime import timedelta
import os,sys,codecs
today_date= date.today()
yesterday_date = today_date - timedelta(days = 1)
yesterday_date=yesterday_date.strftime('%Y%m%d')
today_date=today_date.strftime('%Y%m%d')


#获取本地路径下的基础数据
def joinPath(fileName):
    filePath=os.path.join(sys.path[0],fileName)
    return filePath

def ReadFile(filePath):
    with codecs.open(filePath, "r") as f:
        return f.read()
def WriteFile(filePath, u, encoding="utf-8"):
    # with codecs.open(filePath,"w",encoding) as f:
    with codecs.open(filePath, "wb") as f:
        f.write(u.encode(encoding, errors="ignore"))
def CSV_2_UTF8(src, dst):
    content = ReadFile(src)
    WriteFile(dst, content, encoding="utf-8")




CSV_2_UTF8(joinPath("compactInfo"+"_"+today_date+".csv"),joinPath("compactInfo"+"_"+today_date+"_utf.csv"))
CSV_2_UTF8(joinPath("positionInfo"+"_"+today_date+".csv"),joinPath("positionInfo"+"_"+today_date+"_utf.csv"))
CSV_2_UTF8(joinPath("担保品信息"+".csv"),joinPath("担保品信息"+"_utf.csv"))
CSV_2_UTF8(joinPath("信用资产"+".csv"),joinPath("信用资产"+"_utf.csv"))

融券合约路径=joinPath("compactInfo"+"_"+today_date+"_utf.csv")
持仓路径=joinPath("positionInfo"+"_"+today_date+"_utf.csv")
融资融券合约=pd.read_csv(融券合约路径)
持仓=pd.read_csv(持仓路径)
担保品信息路径=joinPath("担保品信息"+"_utf.csv")
信用资产路径=joinPath("信用资产"+"_utf.csv")
担保品信息=pd.read_csv(担保品信息路径)
信用资产=pd.read_csv(信用资产路径)


# 未还融券代码列表=set(融资融券合约[融资融券合约["未还合约数量"]>0 ]["securityID"].tolist())
# print(未还融券代码列表)
# 

# 拉取数据
ts.set_token("ea368b096e82255de7b26daf8a0c82575187ce88d8773a30c26449a6")
pro = ts.pro_api()
df = pro.daily(**{"ts_code": "","trade_date": "20230516","start_date": "","end_date": "","offset": "","limit": ""}, fields=[
    "ts_code","trade_date","open","high","low","close","pre_close","change","pct_chg","vol","amount"])
df["securityID"]=df["ts_code"]
含行情融资融券合约=pd.merge(融资融券合约, df, on=['securityID'], how='left')
含行情融资融券合约["融券市值"]=含行情融资融券合约["未还合约数量"]*含行情融资融券合约["close"]
含行情融资融券合约["融券占用保证金"]=含行情融资融券合约["融券市值"]*含行情融资融券合约["保证金比例"]
含行情融资融券合约["融券卖出金额"]=含行情融资融券合约["合约开仓金额"]
含行情融资融券合约["融券浮盈"]=含行情融资融券合约["合约开仓金额"]-含行情融资融券合约["合约开仓金额"]
担保品信息.rename(columns={'strSecurityID': 'SecurityID'}, inplace=True)
含折算率持仓信息=pd.merge(持仓, 担保品信息, on=['securityID'], how='left')
含折算率持仓信息["折算后担保市值"]=含折算率持仓信息["当前市值"]*含折算率持仓信息["担保品折算率"]

print(含行情融资融券合约)

# 含行情融资融券合约.to_csv(r"C:\Users\AXZQ\Desktop\margin\uiui.csv",index=False)

